package push;

import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;


import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import config.CommonValue;

/**
 * Created by TJ on 2016/6/14.
 */
public class DetectTools {
    /**
     * 传达百度云推送连接/腾讯信鸽注册情况
     * @param context
     * @param connectStatus
     */
    public static void sendPushConnectBroadcast(Context context, String connectStatus) {
        Intent baiduConnect = new Intent(CommonValue.PUSH_CONNECT_ACTION);
        baiduConnect.putExtra(CommonValue.PUSH_CONNECT_STATUS, connectStatus);
        context.sendBroadcast(baiduConnect);//百度云推送连接情况
    }

    /**
     * 判断应用程序是否在前台
     * @param context
     * @return
     */
    public static boolean isAppRunningForeground(Context context){
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Service.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfoList = activityManager.getRunningAppProcesses();
        if (runningAppProcessInfoList==null)
            {
                return false;
            }
        for (ActivityManager.RunningAppProcessInfo processInfo : runningAppProcessInfoList)
        {
            if (processInfo.processName.equals(context.getPackageName())
                    && processInfo.importance==ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND)
            {
                return true;
            }
        } return false;
    }
    /**
     * 网络是否已连接
     * @param context
     * @return
     */
    public static boolean isInternetConnected(Context context) {
        ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo active = connManager.getActiveNetworkInfo();
        boolean hasNetwork = active != null && active.isAvailable() && active.isConnected();
        if (CommonValue.isDebug) Log.i("DetectTools", "Current Network Connected: "+hasNetwork);
        return hasNetwork;
    }

    /**
     * 定时多少毫秒之后触发广播
     * @param context
     * @param receiverClass
     * @param afterMillis 指定毫秒之后触发
     * @param <T>
     */
    public static <T extends BroadcastReceiver> void setTimeout(Context context, Class<T> receiverClass, long afterMillis) {
        if (afterMillis < 1000) throw new IllegalArgumentException("Argument [afterMillis] must be equal or greater than 1S");
        final Context appContext = context.getApplicationContext();
        Intent intent = new Intent(appContext, receiverClass);
        intent.setPackage(appContext.getPackageName());
        PendingIntent pi = PendingIntent.getBroadcast(appContext, 0, intent, 0);
        AlarmManager manager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
        long triggerAtTime = SystemClock.elapsedRealtime() + afterMillis;
        final int SDK_INT = Build.VERSION.SDK_INT;//当前SDK版本
        if (SDK_INT < Build.VERSION_CODES.KITKAT) {
            manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
            if (CommonValue.isDebug) Log.i("DetectTools", "setTimeout -> set - Current SDK Version: "+ SDK_INT);
        } else if (SDK_INT >= Build.VERSION_CODES.KITKAT && SDK_INT < Build.VERSION_CODES.M) {
            manager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
            if (CommonValue.isDebug) Log.i("DetectTools", "setTimeout -> setExact - Current SDK Version: "+ SDK_INT);
        } else if (SDK_INT >= Build.VERSION_CODES.M) {
            manager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
            if (CommonValue.isDebug) Log.i("DetectTools", "setTimeout -> setExactAndAllowWhileIdle - Current SDK Version: "+ SDK_INT);
        }
    }

    /**
     * 取消正在执行的服务
     * @param context
     * @param receiverClass
     * @param <T>
     */
    public static <T extends BroadcastReceiver> void clearTimeout(Context context, Class<T> receiverClass) {
        final Context appContext = context.getApplicationContext();
        Intent intent = new Intent(appContext, receiverClass);
        PendingIntent pi = PendingIntent.getBroadcast(appContext, 0, intent, 0);
        AlarmManager manager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
        manager.cancel(pi);//取消正在执行的服务
        if (CommonValue.isDebug) Log.i("DetectTools", "clearTimeout -> cancel");
    }



    /**
     * 判断某个service是否运行
     * @param context
     * @param serviceClassName
     * @return
     */
    public static boolean isServiceRunning(Context context, String serviceClassName) {
        return isServiceRunning(context, serviceClassName, 500);
    }
    /**
     * 判断某个service是否运行
     * @param context
     * @param serviceClassName
     * @param maxNum
     * @return
     */
    public static boolean isServiceRunning(Context context, String serviceClassName, int maxNum) {
        ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServices = activityManager.getRunningServices(maxNum);
        if (runningServices == null || runningServices.size() == 0) return false;
        for (ActivityManager.RunningServiceInfo serviceInfo : runningServices) {
            if (serviceInfo.service.getClassName().equals(serviceClassName)) return true;
        }
        return false;
    }



    /**
     * 百度云推送服务器IP
     */
    private static final String default_sa = "sa.tuisong.baidu.com";
    private static final String[] standby_sas = new String[]{"sa0.tuisong.baidu.com",
            "sa1.tuisong.baidu.com", "sa2.tuisong.baidu.com", "sa3.tuisong.baidu.com",
            "sa4.tuisong.baidu.com", "sa5.tuisong.baidu.com", "sa6.tuisong.baidu.com",
            "sa7.tuisong.baidu.com", "sa8.tuisong.baidu.com", "sa9.tuisong.baidu.com"};
    public static final int default_sa_port = 5287;
    public static final int standby_sa_port = 5288;
    public static final int port_80 = 80;
    public static final String[] sa_ips = new String[] {
            "202.108.23.105", "180.149.132.107", "111.13.12.162",
            "180.149.131.209", "111.13.12.110", "111.13.100.86",
            "111.13.100.85", " 61.135.185.18", "220.181.163.183",
            "220.181.163.182", "115.239.210.219", "115.239.210.246" };


    private static boolean isIPOK(String establishedNet, String ip, boolean with80) {
        if (establishedNet.contains(ip+":"+default_sa_port)) return true;
        if (establishedNet.contains(ip+":"+standby_sa_port)) return true;
        if (with80 && establishedNet.contains(ip+":"+port_80)) return true;
        return false;
    }



    /**
     * 检测本地的网络连接
     * @param established
     * @return
     */
    public static ArrayList<String> statNet(boolean established) {
        final String netstat_cmd = "netstat -ant";
        ArrayList<String> netList = execCommand(netstat_cmd);
        if (!established) return netList;
        for (int i = netList.size()-1; i >= 0; i--) {
            if (!netList.get(i).contains("ESTABLISHED")) {
                netList.remove(i);
            }
        }
        return netList;
    }

    /**
     * 执行命令行
     * @param command
     * @return
     */
    public static ArrayList<String> execCommand(String command) {
        ArrayList<String> arrayList = new ArrayList<String>();
        InputStreamReader isReader = null;
        LineNumberReader lineReader = null;
        try {
            Process process = Runtime.getRuntime().exec(command);
            isReader = new InputStreamReader(process.getInputStream(), "utf-8");
            lineReader = new LineNumberReader(isReader);
            String line = null;
            while ((line = lineReader.readLine()) != null) {
                arrayList.add(line);
            }
            process.waitFor();
        } catch (Exception e) {
            if (CommonValue.isDebug) e.printStackTrace();
        } finally {
            if (isReader != null) {
                try {
                    isReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return arrayList;
    }
}
